package news.interceptor;

import com.fasterxml.jackson.databind.ObjectMapper;
import news.model.CommonResult;
import news.util.JWTUtil;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class UserTokenInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        String adminToken = request.getHeader("userToken");
        boolean res = JWTUtil.verify(adminToken);

        if(res){
            return true;
        }
        //向前端发起响应
        response.setContentType("text/html;charset=utf-8");
        CommonResult commonResult = new CommonResult(501,"用户token认证失败");
        response.getWriter().write(new ObjectMapper().writeValueAsString(commonResult));
        return false;
    }
}
